package mylab.utils.common;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

@UtilityClass
public class DbEscapeUtil {

    public <T> T mysql(T source) {
        if (source == null) {
            return null;
        }

        Class<?> srcClass = source.getClass();
        Field[] fields = cn.hutool.core.util.ReflectUtil.getFields(srcClass);
        for (Field field : fields) {
            Object classValue = cn.hutool.core.util.ReflectUtil.getFieldValue(source, field);
            if (classValue == null) {
                continue;
            }
            //final 和 static 字段跳过
            if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if (!(classValue instanceof String srcValue)) {
                continue;
            }

            String tarValue = mysql(srcValue);
            ReflectUtil.setFieldValue(source, field, tarValue);
        }
        return source;
    }

    public String mysql(String keyWord) {
        if (StrUtil.isBlank(keyWord)) return keyWord;
        keyWord = keyWord.replace("\\", "\\\\");
        keyWord = keyWord.replace("/", "\\/");
        keyWord = keyWord.replace("'", "\\'");
        keyWord = keyWord.replace("\"", "\\\"");
        keyWord = keyWord.replace(":", "\\:");
        keyWord = keyWord.replace(";", "\\;");
        keyWord = keyWord.replace(":", "\\:");
        keyWord = keyWord.replace("(", "\\(");
        keyWord = keyWord.replace(")", "\\)");
        keyWord = keyWord.replace("[", "\\[");
        keyWord = keyWord.replace("]", "\\]");

        keyWord = keyWord.replace("@", "\\@");
        keyWord = keyWord.replace("&", "\\&");

        keyWord = keyWord.replace("%", "\\\\%");
        keyWord = keyWord.replace("_", "\\\\_");

        return keyWord;
    }

    public String sqlite(String keyWord) {
        if (StrUtil.isBlank(keyWord)) return keyWord;
        keyWord = keyWord.replace("/", "//");
        keyWord = keyWord.replace("'", "''");
        keyWord = keyWord.replace("[", "/[");
        keyWord = keyWord.replace("]", "/]");
        keyWord = keyWord.replace("%", "/%");
        keyWord = keyWord.replace("&", "/&");
        keyWord = keyWord.replace("_", "/_");
        keyWord = keyWord.replace("(", "/(");
        keyWord = keyWord.replace(")", "/)");
        return keyWord;
    }

}
